package com.linln.wtp.controller.shops;

import com.alibaba.fastjson.JSONObject;
import com.linln.common.utils.GeoUtil;
import com.linln.common.utils.ObjectUtil;
import com.linln.common.utils.PathMappingUtil;
import com.linln.common.vo.JsonResult;
import com.linln.component.wtpshiro.annotation.PassToken;
import com.linln.component.wtpshiro.annotation.UserLoginToken;
import com.linln.modules.area.domain.Area;
import com.linln.modules.area.service.AreaService;
import com.linln.modules.capital.service.ShopCapitalService;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.service.ShopReviewedService;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.wtpshop.service.ShopService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.user.shops
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.user.shops
 * @Description: TODO
 * @date Date : 2020年11月23日 10:49
 */
@Controller("userShopsController")
@RequestMapping("/shops")
public class ShopsController {

    @Autowired
    @Qualifier("shopService")
    private ShopService shopService;


    @Autowired
    private AreaService areaService;
    @Autowired
    private ShopsService shopsService;

    @Autowired
    private ShopReviewedService shopReviewedService;

    @Autowired
    private ShopCapitalService shopCapitalService;

    /**
     * 查看店铺 按距离排序 近的再前
     *
     * @param lon      经度
     * @param lat      纬度
     * @param areaId   地区id
     * @param shopType 店铺类型
     * @param pageNum  第几页
     * @param limit    每页显示多少
     * @return map
     */
    @PassToken
    @ResponseBody
    @GetMapping("/distance")
    public Map<String, Object> getShopsByDistance(@RequestParam("lon") String lon, @RequestParam("lat") String lat, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit, @RequestParam(required = false) Integer areaId, @RequestParam(value = "shopType", required = false) Integer shopType, @RequestParam(value = "reserve", defaultValue = "0") Integer reserve) {
        areaId = checkAreaId(lon, lat, areaId);
        return shopService.getNearbyShops(lon, lat, pageNum, limit, areaId, shopType, reserve);
    }

    /**
     * 查看店铺 按距离排序 近的再前 查看5条
     *
     * @param lon 经度
     * @param lat 纬度
     * @return
     */
    @PassToken
    @ResponseBody
    @GetMapping("/fiveDistance")
    public Map<String, Object> getShopsByDistance(@RequestParam("lon") String lon, @RequestParam("lat") String lat) {
        return shopService.getFiveNearbyShops(lon, lat);
    }

    /**
     * 获取店铺列表 根据评分排序 高的在前
     *
     * @param lon     经度
     * @param lat     纬度
     * @param pageNum 第几页
     * @param limit   每页多少条数据
     * @return 店铺列表
     */
    @PassToken
    @ResponseBody
    @GetMapping("/score")
    public Map<String, Object> getShopOrderScore(@RequestParam("lon") String lon, @RequestParam("lat") String lat, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit, @RequestParam(required = false) Integer areaId, @RequestParam(value = "shopType", required = false) Integer shopType, @RequestParam(value = "reserve", defaultValue = "0") Integer reserve) {
        areaId = checkAreaId(lon, lat, areaId);
        return shopService.getShopOrderScore(lon, lat, pageNum, limit, areaId, shopType, reserve);
    }


    /**
     * 获取店铺列表
     *
     * @param lon     经度
     * @param lat     纬度
     * @param pageNum 第几页
     * @param limit   每页多少条数据
     * @return 店铺列表
     */
    @PassToken
    @ResponseBody
    @GetMapping("/shopType")
    public Map<String, Object> getShopsByShopType(@RequestParam("lon") String lon, @RequestParam("lat") String lat, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit, @RequestParam(required = false) Integer areaId, @RequestParam(value = "shopType", required = false) Integer shopType) {
        areaId = checkAreaId(lon, lat, areaId);
        return shopService.getShopsByShopType(lon, lat, pageNum, limit, areaId, shopType);
    }


    /**
     * @param lon      经度
     * @param lat      纬度
     * @param pageNum  第几页
     * @param limit    每页多少条数据
     * @param areaId   地区id
     * @param shopName 店铺名称模糊查询
     * @return 店铺列表
     */
    @PassToken
    @ResponseBody
    @GetMapping("/searchShop")
    public Map<String, Object> searchShop(@RequestParam("lon") String lon, @RequestParam("lat") String lat, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit, @RequestParam(required = false) Integer areaId, @RequestParam(value = "shopName", required = false) String shopName) {
        areaId = checkAreaId(lon, lat, areaId);
        return shopService.getShopsByShopName(lon, lat, pageNum, limit, areaId, shopName);
    }

    //如果没有传地区id  那么通过经度纬度 获取用户所在的地区  查询这个地区的数据
    private Integer checkAreaId(String lon, String lat, Integer areaId) {
        Integer newAreaId = areaId;
        if (areaId == null) {
            String cityByAddress = GeoUtil.getLatAndLng(lon, lat).getJSONObject("address_component").getString("city");
            Area area = areaService.getAreaByName(cityByAddress);
            if (area != null && area.getAreaId() != null) {
                newAreaId = area.getAreaId();
            }
        }
        return newAreaId;
    }

    @Value("${server.ip}")
    private String ip;

    @GetMapping("/shopInfo")
    @ResponseBody
    @UserLoginToken
    public JsonResult getShopInfo(@RequestParam("shopId") String shopId) {
        Map<String, Object> map = new HashMap<>();
        Shops byId = shopsService.getById(shopId);
        Map propMap = JSONObject.parseObject(byId.getProps(), Map.class);
        if (byId.getOpeningStatus() == null) {
            byId.setOpeningStatus("1");
        }
        List<String> imgs = new ArrayList<>();
        String img1 = byId.getShopPicture();
        String img2 = (String) propMap.get("constructionworkshopMapping");
        String img3 = (String) propMap.get("technicianconstructionMapping");
        if (Strings.isNotBlank(img1)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img1));
        }
        if (Strings.isNotBlank(img2)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img2));
        }
        if (Strings.isNotBlank(img3)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img3));
        }
        map.put("imgs", imgs);
        map.put("shopInfo", byId);
        map.put("shopCapital", shopCapitalService.getShopCapitalByShopId(shopId));
        return JsonResult.ok().put("data", map);
    }

    @GetMapping("/myShopInfo")
    @ResponseBody
    @UserLoginToken
    public JsonResult getMyShopInfo(@RequestParam("shopId") String shopId) throws IllegalAccessException, JSONException, InvocationTargetException {
        Map<String, Object> map = new HashMap<>();
        Shops byId = shopsService.getById(shopId);
        String[] serveListValue = byId.getShopType().split(",");
        byId.setShopType(shopReviewedService.selectShopType(shopId));
        Map propMap = JSONObject.parseObject(byId.getProps(), Map.class);
        if (byId.getOpeningStatus() == null) {
            byId.setOpeningStatus("1");
        }
        List<String> imgs = new ArrayList<>();
        String img1 = byId.getShopPicture();
        String img2 = (String) propMap.get("constructionworkshopMapping");
        String img3 = (String) propMap.get("technicianconstructionMapping");
        String img4 = (String) propMap.get("businesslicenseMapping");
        if (Strings.isNotBlank(img4)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img4));
        }
        if (Strings.isNotBlank(img1)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img1));
        }
        if (Strings.isNotBlank(img2)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img2));
        }
        if (Strings.isNotBlank(img3)) {
            imgs.add(PathMappingUtil.formatUrl(ip, img3));
        }
        Map map1  = ObjectUtil.ObjectToMap(byId);
        map1.put("serveListValue",serveListValue);
        map.put("isUpdating",false);
        if(map1.containsKey("newShop")){
            if(map1.get("newShop")!=null){
                map.put("isUpdating",true);
            }
        }
        map.put("imgs", imgs);
        map.put("shopInfo", map1);
        return JsonResult.ok().put("data", map);
    }


    //更改营业状态
    @PostMapping("/opening")
    @ResponseBody
    public JsonResult updateOpeningStatus(@RequestParam String shopId, @RequestParam Integer status) {
        return shopService.updateOpeningStatus(shopId, status) ? JsonResult.ok() : JsonResult.error();
    }

}
